package com.sopt.test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;

import com.sopt.test.http.HttpManager;
import com.sopt.test.http.MsgManager;
import com.sopt.test.member.ContactAdder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private HttpManager httpMananger;
    private MsgManager msgManager;
    private MyDataSetObserver mObserver = new MyDataSetObserver();
    private SendMessageSetObserver sObserver = new SendMessageSetObserver();
    
    
    private ListView mContactList;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.main);
        
        init();
    }
    private void init(){
    	httpMananger = HttpManager.getInstance(this);
    	msgManager = MsgManager.getInstance(this);
    	
    	
    	Button btn = (Button)findViewById(R.id.btnCheckExistUser);
    	Button btnSend = (Button)findViewById(R.id.btnSendMessage);
    	Button btnAdder = (Button)findViewById(R.id.btnContactAdder);
    	
    	mContactList = (ListView) findViewById(R.id.contactList);
    	
    	btn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				checkExistUser();
			}
		});
    	
    	btnSend.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try {
					sendMessage();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
    	
    	btnAdder.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(MainActivity.this, ContactAdder.class);
		        startActivity(i);
			}
		});
    	
    	 // Populate the contact list
        populateContactList();
    }
    
    protected void sendMessage() throws UnsupportedEncodingException {
    	EditText et = (EditText)findViewById(R.id.editTextMessage);
    	
    	if(et.getText().toString().length()>0 && !msgManager.isLoading()){
    		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        	imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
        	
    		TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String myNumber = mTelephonyMgr.getLine1Number();
            
            et.setEnabled(false);
            
			msgManager.load(TestVars.HOST_URL+TestVars.ACTION_SEND_MSG+"?content="+URLEncoder.encode(et.getText().toString(), "UTF-8")+"&number="+myNumber);
			
			toggleLoadingStatus();
			
			if(msgManager.isLoading())msgManager.addObserver(sObserver);
    	}else if(msgManager.isLoading()){
    		alert("전송중입니다.");
    	}else{
    		alert("글자를 입력해주세요");
		}
	}
    
	private void checkExistUser(){
		if(!httpMananger.isLoading()){
			TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
	        String myNumber = mTelephonyMgr.getLine1Number();
	        
	        httpMananger.load(TestVars.HOST_URL+TestVars.ACTION_CHECK_EXIST_MEMBER+"?number="+myNumber);
	        toggleLoadingStatus();
	        if(httpMananger.isLoading())httpMananger.addObserver(mObserver);
		}else{
			alert("요청중입니다.");
		}
    }
	
	public void toggleLoadingStatus(){
		if (httpMananger.isLoading() || msgManager.isLoading()) {
        	setProgressBarIndeterminateVisibility(httpMananger.isLoading() || msgManager.isLoading());
        }else{
        	setProgressBarIndeterminateVisibility(false);
        }
	}
	
	public void alert(String msg){
		if(msg.length()>0)Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
	}
	
	public Intent getContactIntent() {
 		return(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI));
 	}
	
	
	
	private Cursor getContacts()
    {
        // Run query
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String[] projection = new String[] {
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME
        };
        
        
        
        String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" +
                ("1") + "'";
        String[] selectionArgs = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

        
        return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
    }
	
	private void populateContactList() {
        // Build adapter with contact entries
        Cursor cursor = getContacts();
        String[] fields = new String[] {
                ContactsContract.Data.DISPLAY_NAME
        };
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_item, cursor,
                fields, new int[] {R.id.contactEntryText});        
        
        mContactList.setAdapter(adapter);
    }
    
    
    private class MyDataSetObserver extends DataSetObserver {
        public void onChanged() {
        	Log.v("changdoc", "in MyDataSetObserver"+httpMananger.size());
        	toggleLoadingStatus();
        	
            JSONObject json = new JSONObject(httpMananger.get(httpMananger.size()-1));
            
            TextView tv = (TextView) findViewById(R.id.textView);
            
			try {
				tv.setText(json.getString("exist"));
				
				alert( json.getString("exist") );
				
				httpMananger.clear();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Log.v("changdoc", "ERROR JSON PARSE");
			}
        }
        public void onInvalidated() {
        }
    }
    
    private class SendMessageSetObserver extends DataSetObserver {
        public void onChanged() {
        	toggleLoadingStatus();
        	
        	Log.v("changdoc", "in Send MessageSetObserver");
        	
        	JSONObject json = new JSONObject(msgManager.get(msgManager.size()-1));
        	try {
				alert(json.getString("CONTENT"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			EditText et = (EditText)findViewById(R.id.editTextMessage);
			et.setText("");
			et.setEnabled(true);
        	
        	msgManager.clear();
        }
        public void onInvalidated() {
        }
    }
}